//
// Created by liaohailong on 2025/4/11.
//

#ifndef HELLOVIDEOCACHE_HELLODATAFETCHER_HPP
#define HELLOVIDEOCACHE_HELLODATAFETCHER_HPP

#include <thread>
#include <atomic>

#include "../net/HelloHttpRequest.hpp"
#include "../net/CSApp.hpp"
#include "../cache/HelloCacheManager.hpp"

/**
 * create by liaohailong
 * 2025/4/11 19:21
 * desc: 纯抽象类,负责数据获取
 */
class HelloDataFetcher
{
public:
    typedef void (*OnCompleteCallback)(HelloDataFetcher *fetcher, void *userdata);

    typedef struct
    {
        OnCompleteCallback cb;
        void *userdata;
    } OnCompleteCallbackCtx;
public:
    explicit HelloDataFetcher(const std::shared_ptr<HelloCacheManager> &cache,
                              const std::shared_ptr<HelloHttpRequest> &request,
                              const std::shared_ptr<HelloRange> &range,
                              const char *tag = "HelloClientWriter");

    virtual ~HelloDataFetcher();

    const std::shared_ptr<HelloHttpRequest> &getRequest() noexcept;

    const std::shared_ptr<HelloRange> &getRange() noexcept;

    void setNext(const std::shared_ptr<HelloDataFetcher> &fetcher);

    void setOnCompleteCallback(OnCompleteCallback callback, void *userdata);

    const std::shared_ptr<HelloCacheInfo> &getCacheInfo();

    void start();

    void stop(bool join = true);

    /**
     * 子类实现,处理数据
     */
    virtual bool run(const std::shared_ptr<HelloHttpRequest> &request) = 0;

private:
    void fetch();

protected:
    static std::string getResponseHeader(const std::shared_ptr<HelloRange> &range,
                                         int64_t contentLength, const std::string &type);

    bool sendHeader();

protected:
    Logger logger;
    std::shared_ptr<OnCompleteCallbackCtx> callbackCtx;

    std::shared_ptr<HelloCacheManager> cache;
    std::shared_ptr<HelloHttpRequest> request;
    std::shared_ptr<HelloRange> range;
    std::thread *worker;
    std::atomic<bool> running;

    std::shared_ptr<HelloDataFetcher> next;
};


#endif //HELLOVIDEOCACHE_HELLODATAFETCHER_HPP
